<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>收集表管理</title>
    <link rel="shortcut icon" type="image/x-icon" th:href="@{/static/img/favicon.ico}"/>

    <link rel="stylesheet" type="text/css"
          th:href="@{/plugins/bootstrap/css/bootstrap.min.css}">
    <link rel="stylesheet" type="text/css"
          th:href="@{/plugins/font-awesome/css/font-awesome.min.css}">
    <script th:src="@{/js/jquery.min.js}" crossorigin="anonymous"></script>
    <script th:src="@{/plugins/bootstrap/js/bootstrap.min.js}" crossorigin="anonymous"></script>
    <style>
        body {
            padding: 10px;
        }

        #chooseGroupItemBox {
            display: flex;
            flex-direction: column;
            padding: 0px 10px;

            color: #495057;
            background-color: #fff;
            background-clip: padding-box;
            border: 1px solid #ced4da;
            border-radius: 0.25rem;
        }

        .form-check {
            display: flex;
            align-items: center;
        }

        #top_page_control {
            display: flex;
            justify-content: flex-start;
            margin: 10px 10px;
            flex-wrap: nowrap;
            align-items: center;
        }

        #top_page_control > * {
            display: block;
            margin-right: 10px;
        }

        i {
            display: inline-block;
            margin-right: 5px;
        }

        #consoleCollectSearchInput {
            width: 30%;
        }


        .paging {
            position: fixed;
            bottom: 0px;
            left: 50%;
            transform: translateX(-50%);
        }

        .page_view {
            height: 31px;
            line-height: 31px;
            margin: 0px 10px;
        }

        .table {
            margin-bottom: 80px;
            opacity: 0.8;
        }
        .collect-detail-control {
            display: flex;
            justify-content: flex-end;
            align-items: center;
            margin-bottom: 20px;
        }
        .form-select {
            width: 120px;
        }
        #collectUserSearchInput {
            flex-grow: 3;
        }
        #collectUserSearchButton {
            text-wrap: nowrap;
        }
        .collect-detail-control > * {
            margin: 0px 5px;
        }
        #page-control {
            display: flex;
            justify-content: space-around;
            align-items: center;
        }
        #page-control > i {
            cursor: pointer;
            padding: 0px 10px;
        }




    </style>
</head>
<body>
<div id="top_page_control">
    <input type="text" class="form-control" name="keyword" id="consoleCollectSearchInput"
           placeholder="搜索创建的收集活动...">
    <button class="btn btn-primary btn-sm" data-toggle="modal" id="searchConsoleCollectButton">
        <i class="fa fa-search" aria-hidden="true"/></i>搜索收集
    </button>
    <button class="btn btn-primary btn-sm" data-toggle="modal" id="addCollectButton">
        <i class="fa fa-plus"></i>添加收集表
    </button>
</div>

<table class="table table-hover">
    <thead>
    <tr>
        <th scope="col">#</th>
        <th scope="col">收集标题</th>
        <th scope="col">开始时间</th>
        <th scope="col">结束时间</th>
        <th scope="col">收集进度</th>
        <th scope="col">操作</th>
    </tr>
    </thead>
    <tbody>

    </tbody>
</table>

<ul class="pagination justify-content-center paging">
    <li class="page-item">
        <button class="page-link" id="pre_page">上一页</button>
    </li>
    <div class="page-item page_view">
        <input value="1" name="custom_page" style="width: 30px"> / <span id="maxPage">0</span>
    </div>
    <li class="page-item ">
        <button class="page-link" href="#" id="custom_page">跳转</button>
    </li>
    <li class="page-item">
        <button class="page-link" id="next_page">下一页</button>
    </li>
</ul>

<div class="modal fade" id="collectModal" data-backdrop="static" data-keyboard="false" tabindex="-1"
     aria-labelledby="staticBackdropLabel" aria-hidden="true">
    <div class="modal-dialog ">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="staticBackdropLabel">创建收集表</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
            </div>

            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="submitCollect" collect_id="">确认</button>
            </div>
        </div>
    </div>


</div>

<script type="module">
    import {POST, GET, POST_FORM} from "/js/request.js";
    import {formatDate, formatDateTTime} from "/js/formatDate.js";
    import {bootstrapModalController} from "/js/bootstrapModalController.js";

    let pageVars = {
        currentPage: 1,
        pageSize: 10,
        keyword: '',
        total: 0
    }
    let list = []
    let pageModal = {
        modalBox: "#collectModal"
    }


    $("#next_page").click(function () {
        if (pageVars.currentPage + 1 > getMaxPage()) {
            return;
        }
        pageVars.currentPage++
        refreshCollectList();
    })
    $("#pre_page").click(function () {
        if (pageVars.currentPage - 1 < 1) {
            return;
        }
        pageVars.currentPage--
        refreshCollectList();
    })
    $("#custom_page").click(function () {
        let customPage = $("input[name='custom_page']").val()
        if (customPage < 1 || customPage > getMaxPage()) {
            return
        }
        pageVars.currentPage = customPage
        refreshCollectList();

    })
    // 点击搜索
    $("#searchConsoleCollectButton").click(function () {
        pageVars.keyword = $("input[name='keyword']").val();
        // 将当前页置0
        pageVars.currentPage = 1
        refreshCollectList();
    })

    function getMaxPage() {
        return Math.ceil(pageVars.total / pageVars.pageSize)
    }

    function refreshPageParamToView() {
        $("#maxPage").text(getMaxPage())
        $("input[name='custom_page']").val(pageVars.currentPage)
    }

    function collectIdToCollectObject(collectId) {
        for (let collect of list) {
            if ("" + collect.id === "" + collectId) return collect;
        }
        return null;
    }

    refreshCollectList();

    function refreshCollectList() {
        $("table > tbody").html('')
        GET("/collect/consoleCollectPageData", pageVars).then(result => {
            if (result.success) {
                console.log("分页数据：", result.data)
                list = result.data.list;
                pageVars.total = result.data.total;
                let viewBox = $("table > tbody");
                let index = 0;
                list.forEach(item => {
                    viewBox.append(`
                         <tr>
                            <th scope="row">${++index}</th>
                            <td>${item.title}</td>
                            <td>${formatDate(new Date(item.startTime), 'yyyy-MM-dd HH:mm')}</td>
                            <td>${formatDate(new Date(item.endTime), 'yyyy-MM-dd HH:mm')}</td>
                            <td>${item.completedCount} / ${item.userCount}</td>
                            <td>
                                <button class="btn btn-primary btn-sm seeCollectDetailButton" collect_id="${item.id}" >
                                    <i class="fa fa-eye" aria-hidden="true" /></i></i>详情
                                </button>
                                <button class="btn btn-primary btn-sm export_button" collect_id="${item.id}" ${item.completedCount == 0 ? 'disabled' : ''} >
                                    <i class="fa fa-cloud-download" aria-hidden="true" /></i>导出
                                </button>

                                <button type="button" class="btn btn-primary btn-sm expediting_button" collect_id="${item.id}" ${(Date.now() > new Date(item.endTime).getTime() || item.userCount == item.completedCount)?'disabled' : ''} >
                                    <i class="fa fa-file-audio-o" aria-hidden="true" /></i>一键催收
                                </button>

                                <button class="btn btn-primary btn-sm editCollectButton" collect_id="${item.id}" >
                                    <i class="fa fa-edit" aria-hidden="true" /></i>编辑
                                </button>

                                 <button class="btn btn-danger btn-sm remove_collect_button" collect_id="${item.id}" >
                                    <i class="fa fa-remove" aria-hidden="true" /></i>删除
                                </button>
                            </td>
                        </tr>
                    `)
                })

            }
            refreshPageParamToView()
        })
    }


    // 点击新增活动
    $("#addCollectButton").click(function () {
        collectForm(null)
    })
    // 点击收集活动的编辑
    $("table > tbody").on("click", ".editCollectButton", function () {
        let collectId = $(this).attr("collect_id");
        let collect = collectIdToCollectObject(collectId);
        if (collect == null) refreshCollectList();
        collectForm(collect)
    })

    function editCollect(submitForm,close) {
        console.log("要提交的表单数据：",submitForm)
        POST("/collect/edit", submitForm).then(result => {
            if (result.success) {
                refreshCollectList();
                close();
            } else {
                alert(result.message)
            }
        })
    }

    function addCollect(submitForm,close) {
        POST("/collect/create", submitForm).then(result => {
            if (result.success) {
                alert("收集活动创建成功，已通知相关用户！")
                refreshCollectList();
                close();
            } else {
                alert(result.message)
            }
        })
    }



    // 点击查看活动数据
    $("table > tbody").on("click", ".seeCollectDetailButton", function () {

        let collectId = $(this).attr("collect_id");
        let list = []
        let total = 0;
        let collectUserPageVar = {
            currentPage: 1,
            pageSize: 20,
            keyword: '',
            collectId: collectId,
            status: -1, // 0 是未提交 1是已提交
            groupId: -1
        }
        function getMaxPage() {
            return Math.ceil(total / collectUserPageVar.pageSize);
        }




        bootstrapModalController({...pageModal,size: "modal-ll",buttonController:{hidden:true}}, "收集活动详情",`
            <div class="collect-detail-control">
                <input type="text" class="form-control" id="collectUserSearchInput" value="" placeholder="请输入参与者姓名搜索..." >
                <select class="custom-select form-select group-select">
                  <option value="-1">所有组</option>
                </select>
                <select class="custom-select form-select status-select">
                  <option value="-1">所有状态</option>
                  <option value="0">未提交</option>
                  <option value="1">已提交</option>
                </select>
                <button class="btn btn-primary" id="collectUserSearchButton" ><i class="fa fa-search" aria-hidden="true" /></i>搜索</button>
                <div id="page-control">
                    <i class="fa fa-arrow-left" aria-hidden="true" id="collectUserLastPageButton" /></i>
                    <i class="fa fa-arrow-right" aria-hidden="true" id="collectUserNextPageButton"  /></i>
                </div>
            </div>
            <div>
            <table class="table table-striped collect-user-table">
              <thead>
                <tr>
                  <th scope="col">#</th>
                  <th scope="col">学号</th>
                  <th scope="col">姓名</th>
                  <th scope="col">性别</th>
                  <th scope="col">所属组</th>
                  <th scope="col">提交状态</th>
                  <th scope="col">操作</th>
                </tr>
              </thead>
              <tbody>
              </tbody>
            </table>
            </div>
        `,function (close,{}) { })
        let tbody = $(".collect-user-table tbody")
        // 收集活动用户信息-点击搜索
        $("#collectUserSearchButton").click(function () {
            collectUserPageVar.keyword =  $("#collectUserSearchInput").val();
            // 重置页
            collectUserPageVar.currentPage = 1
            refreshCollectUserPage();
        })


        // 显示相关联的组到select
        GET(`/collect/selectCollectGroupList/${collectId}`).then(result=>{
            if (result.success) {
                // 将组信息显示到select标签下中
                let collectGroupList = result.data
                let groupSelect = $(".collect-detail-control .group-select")
                collectGroupList.forEach(collectGroup => {
                    groupSelect.append(`<option value="${collectGroup.groupId}">${collectGroup.groupName}</option>`)
                })
            }else {
                alert("获取收集活动相关联的组信息失败！")
            }
        })
        // 两个分页按钮
        let lastPageButton = $("#collectUserLastPageButton")
        let nextPageButton = $("#collectUserNextPageButton")
        function pageOperation(inc = 0) {
            let preCurrentPage = collectUserPageVar.currentPage + inc;
            let maxPage = getMaxPage();
            console.log("分页：",maxPage,total)
            if (preCurrentPage > 0 && preCurrentPage < maxPage+1) {
                collectUserPageVar.currentPage = preCurrentPage
            }
            let disabledColor = "#979797";
            if (collectUserPageVar.currentPage == 1) {
                lastPageButton.css("color",disabledColor)
            }else {
                lastPageButton.css("color","#212529")
            }
            if (collectUserPageVar.currentPage >= getMaxPage()) {
                nextPageButton.css("color",disabledColor)
            }else {
                nextPageButton.css("color","#212529")
            }
        }

        // 收集活动用户信息-列表数据刷新
        function refreshCollectUserPage() {

            GET("/collect/collectUserPage",collectUserPageVar).then(result=>{
                if (result.success) {
                    list = result.data.list
                    total = result.data.total
                    let index = 0;
                    // 置空原有tbody内容
                    tbody.html('')
                    for(let item of list) {
                        tbody.append(`
                            <tr>
                              <th scope="row">${++index}</th>
                              <td>${item.studentId}</td>
                              <td>${item.nickname}</td>
                              <td>${item.sex === null?'未知':(item.sex === 1?'男':'女')}</td>
                              <td>${item.groupName}</td>
                              <td>${item.file == null?'未提交':'已提交'}</td>
                              <td>
                                <button type="button" class="btn btn-primary btn-sm userSubmitCollectDownloadButton" download_url="${item.file}?filename=${item.filename}" ${item.file!=null?'':'disabled'}  ><i class="fa fa-cloud-download" aria-hidden="true" /></i>下载查看</button>
                                <button type="button" class="btn btn-primary btn-sm" ${item.file!=null?'disabled':''} onclick="alert('功能暂未实现')"><i class="fa fa-file-audio-o" aria-hidden="true" /></i>催收</button>
                              </td>
                            </tr>
                        `)
                    }
                    // 初始化分页按钮颜色
                    pageOperation();

                    console.log("获取的参与收集活动的用户及活动相关信息：",result.data)

                }else {
                    alert("获取收集活动关联的用户信息失败！")
                }
            })
        }
        // 绑定事件-点击下载某个用户提交的文件
        tbody.on("click",".userSubmitCollectDownloadButton", function () {
            let download_url = $(this).attr("download_url")
            window.open(download_url);
        })
        // 初始化页数量
        refreshCollectUserPage()

        // 分页按钮点击事件
        lastPageButton.click(() => {
            pageOperation(-1)
            refreshCollectUserPage();
        })
        nextPageButton.click(() => {
            pageOperation(1)
            refreshCollectUserPage();
        })
        // 状态改变
        $(".collect-detail-control .status-select").change(function() {
            let newStatus = $(this).val();
            collectUserPageVar.status = newStatus;
            // 重置页数
            collectUserPageVar.currentPage = 1
            refreshCollectUserPage();
        });
        // 查询的组改变
        $(".collect-detail-control .group-select").change(function() {
            let newGroupId = $(this).val();
            collectUserPageVar.groupId = newGroupId;
            // 重置页数
            collectUserPageVar.currentPage = 1
            refreshCollectUserPage();
        });

    })
    // 点击导出
    $("table > tbody").on("click", ".export_button", function () {
        let collectId = $(this).attr("collect_id");
        GET(`/collect/exportCollect/${collectId}`).then(result => {
            if (result.success) {
                let compressDownloadUrl = result.data;
                window.open(compressDownloadUrl)
            } else {
                alert("压缩操作执行失败！" + result.message)
            }
        })
    })
    // 点击一键催收
    $("table > tbody").on("click", ".expediting_button", function () {
        let collectId = $(this).attr("collect_id");
        POST(`/collect/expeditingAll/${collectId}`).then(result => {
            if (result.success) {
                alert(result.message)
            } else {
                alert("催收失败了！" + result.message)
            }
        })
    })
    // 点击删除
    $("table > tbody").on("click", ".remove_collect_button", function () {
        let collectId = $(this).attr("collect_id");
        window.Message(
            "删除收集活动确认",
            "确认要删除吗？",
            function (close) {
                console.log("子容器回调函数")
                POST(`/collect/remove/${collectId}`).then(result => {
                    if (result.success) {
                        close()
                        console.log("刷新列表")
                        refreshCollectList()
                        // 关闭模态框
                    } else {
                        alert("删除失败了！");
                    }
                })
            }
        );
    })

    function collectForm(form = {}) {
        if (form == null) form = {}
        bootstrapModalController(pageModal, "创建收集表",
            `
            <div class="form-group">
                <label for="collectTitle">主题：</label>
                <input type="text" class="form-control" id="collectTitle" name="title"
                       placeholder="请输入要收集的标题..." value="${form.title??''}">
            </div>
            <div class="form-group">
                <label for="collectDesc">描述：</label>
                <textarea rows="6" class="form-control" id="collectDesc" name="desc"
                          placeholder="请输入详细描述..." >${form.describe??''}</textarea>
            </div>
            <div class="form-group">
                <label for="collectDesc">选择收集组：</label>
                <div class="form-group" id="chooseGroupItemBox">

                </div>
            </div>
            <!-- 创建日期选择器 -->
            <div class="input-daterange input-group" id="datepicker">
                <input type="datetime-local" class="form-control" name="start_time" value="${formatDateTTime(new Date(form.startTime))}" placeholder="开始时间">
                <div class="input-group-prepend"><span class="input-group-text">到</span></div>
                <input type="datetime-local" class="form-control" name="end_time" value="${formatDateTTime(new Date(form.endTime))}" placeholder="结束时间">
            </div>
    `, function (close, {title, desc, start_time, end_time, groupItemIds}) {
                let submitForm = {
                    title,
                    describe:desc,
                    startTime:  new Date(start_time).getTime() ,
                    endTime: new Date(end_time).getTime()  ,
                    id: form.id, // 收集活动id
                    groupIds: groupItemIds
                }
                if ( form.id == null ) {
                    // 添加
                    addCollect(submitForm,close);
                } else {
                    // 编辑
                    editCollect(submitForm,close);
                }
            })

        refreshGroupsList(function () {
            if (form != null) {
                // 回显多选框
                GET("/collectGroup/getGroupByCollectId", {collectId: form.id}).then(result => {
                    if (result.success) {
                        // 开始回显关联的组
                        let groupItemIds = $("input[name='groupItemIds']");
                        groupItemIds.val(result.data)
                    }
                })
            }
        })
    }


    // 刷新表单中的可选的组
    function refreshGroupsList(handle) {
        let groupsListBox = $("#chooseGroupItemBox");
        // 选清空内容
        groupsListBox.html('')
        GET(`/groups/getGroupsTree`).then(result => {
            if (result.success) {
                result.data.forEach(groups => {
                    let treeTable = ``;
                    treeTable += `<span  groups_id="${groups.id}">${groups.name}</span><ul>`;
                    if (groups.groupList != null) {
                        groups.groupList.forEach(groupItem => {
                            treeTable += `<li group_id="${groupItem.id}">
                                            <div class="form-check">
                                              <input class="form-check-input" type="checkbox" name="groupItemIds" value="${groupItem.id}" id="${groupItem.id}">
                                              <label class="form-check-label" for="${groupItem.id}">
                                                ${groupItem.name}
                                              </label>
                                            </div>
                                        </li>`
                        })
                    }
                    treeTable += `</ul>`;
                    // 追加显示集合
                    groupsListBox.append(treeTable)
                    if (handle != null) handle();
                })

            }
        })
    }


</script>
</body>
</html>